﻿Imports System.Management
Public Class Currentusr
    Public Shared Function CheckCurrentUser(ByVal strComputer As String) As String
        Dim wmiScope As ManagementScope
        Dim wmiConnectionOptions As New ConnectionOptions
        Dim query As ManagementObjectSearcher
        Dim queryCollection As ManagementObjectCollection
        Dim oq As ObjectQuery
        With wmiConnectionOptions
            .Impersonation = ImpersonationLevel.Impersonate
            .Authentication = AuthenticationLevel.Packet
        End With
        Dim userName As String = ""
        Try
            wmiScope = New ManagementScope("\\" & StrComputer & "\root\cimv2", wmiConnectionOptions)
            oq = New ObjectQuery("select * from Win32_ComputerSystem")
            query = New ManagementObjectSearcher(wmiScope, oq)
            queryCollection = query.Get()
            For Each oReturn As ManagementObject In queryCollection
                If oReturn("UserName").ToString() = Nothing Then
                    userName = "Nobody currently logged on"
                Else
                    userName = oReturn("UserName").ToString()
                End If
            Next
            Return userName
        Catch
            Return "Machine is inaccessable"
        End Try
    End Function
End Class
